package com.lvhr.rpc.filter;

import com.lvhr.rpc.RpcApplication;
import com.lvhr.rpc.model.RpcRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * Token 校验器
 */
@Slf4j
public class TokenValidator implements SecurityValidator {

    private final String token;

    public TokenValidator(String token) {
        this.token = token;
    }

    @Override
    public boolean validate(RpcRequest request) throws SecurityException {
        log.debug("开始token校验 --------------------------------------");
        // 从请求的attachments中获取token
        String token = (String) request.getAttachments().get("token");

        // 获取配置中的有效token
        String validToken = RpcApplication.getRpcConfig()
                .getSecurityConfig()
                .getToken();

        // 进行校验
        if (validToken == null && !validToken.equals(token)) {
            throw new SecurityException(401, "无效的Token");
        }
        return true;
    }
}

